<?php

/**
 * SiteController is the default controller to handle user requests.
 */
class ExamController extends Controller
{
	/**
	 * Declares class-based actions.
	 */

    public function actions(){
	}
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}
    public function actionFinal($id)
    {   
        //$exam=Exam::model()->findByPk($id);
        //$model=$exam->completions;
        $model=Exam::model()->with('completions')->findByPk($id);
        $this->render('final', array('model'=>$model));
    }
    
    public function actionCreate()
    {      
        
        $this->render('create');
    }
    
    public function actionQuestionnaire($id)
    {      
        echo Yii::app()->user->getId();
        //echo (Yii::app()->user->isAdmin())? 'isAdmin':'no';
        echo (Yii::app()->user->isGuest)? 'isGuest':'noBody';
        if(Yii::app()->user->checkAccess('updatePost'))
            echo Yii::app()->user->checkAccess('readExam').'read';
        $model=Exam::model()->findAll('questionnaire='.$id);
        $this->render('questionnaire',array('model'=>$model));
        
    }
    
    public function actionNext($id)
    {      
        $model=Exam::model()->findBySql('SELECT id from tbl_exam where questionnaire ='.$id.' and type = 1');
        if($model == null) {
            $model=new Exam;
            $model->questionnaire=$id;
            $model->user=2; 
            $model->type=1;
        
            $model->save();
        }
        $this->render('next',array('model'=>$model));
    }
    public function actionAnswer($id)
    {
        // collect user input data
        $exam=Exam::model()->findByPk($id);
        $model=new AnswerForm();
        $completion=new Completion;
	if(isset($_POST['AnswerForm']))
	{
            $model->attributes=$_POST['AnswerForm'];
            $completion=Completion::model()->findBySql('Select * from tbl_completion where exam='.$model->theExam.' and question='.$model->theId);
            if($completion == null) $completion=new Completion;
            $completion->setAnswer($model);
	}
        $q=$completion->getQuestion($id, $exam->type, $exam->questionnaire);
        if($q['stats']['rest']>0){

            $model->theQuestion = $q['model']->question;
        }
        else {
            $this->redirect(array('exam/final/id/'.$id));
        }
        
        $model->theId = $q['model']->id;  
        $model->theAnswer=$model->theId;
        $model->theExam=$id;
        Yii::app()->session['var'] = 'value';
        $this->render('answer', array('model'=>$model,'stats'=>$q['stats'],'exam'=>$exam));
    }
}
